<!--
* @Description: 学生校园品牌说 编辑
* @Author: liyujie
* @Date: 2021/03/04
* @Last Modified by: liyujie
* @Last Modified time: 2021/03/04
-->
<template>
    <div class="container zdWebsitBrandChange">
        <el-form
            v-if="init"
            ref="mainform"
            :model="formData"
            label-position="right"
            status-icon
            :rules="formRule"
            label-width="110px"
            :disabled="false">
            <div class="form-unit">
                <div class="form-title">品牌说设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="brand_name"
                    label="品牌说名称:"
                >
                    <el-input
                        placeholder="请输入品牌说名称"
                        v-model="formData.brand_name"
                        size="small"
                        class="task-input"
                    />
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="brand_people"
                    label="客户姓名:"
                >
                    <el-input
                        placeholder="请输入客户姓名全名"
                        v-model="formData.brand_people"
                        size="small"
                        class="task-input"
                    />
                </el-form-item>
                <div style="display:flex">
                    <el-form-item
                        class="task-form-item"
                        size="small"
                        prop="company_name"
                        label="客户品牌名:"
                    >
                        <el-input
                            placeholder="请输入客户品牌名"
                            v-model="formData.company_name"
                            size="small"
                            class="task-input"
                        />
                    </el-form-item>
                    <!-- <el-form-item
                        class="task-form-item"
                        size="small"
                        label="客户品牌名:"
                        prop="hire_no"
                    >
                        <el-select
                            v-model="formData.hire_no"
                            size="small"
                            filterable
                            clearable
                            remote
                            reserve-keyword
                            :remote-method="fnGetCompanyList"
                            @change="fnGetIndustry()"
                        >
                            <el-option
                                v-for="item in companyList"
                                :key="item.hire_no"
                                :label="item.company_name"
                                :value="item.hire_no"
                            />
                        </el-select>
                    </el-form-item> -->
                    <el-form-item
                        class="task-form-item"
                        size="small"
                        label="公司行业:"
                        prop="category_id"
                    >
                        <el-cascader
                            v-model="formData.category_id"
                            :options="industryList"
                            :props="{
                                value: 'id',
                                label: 'title',
                                children: 'children'
                            }"
                            expand-trigger="click"
                            clearable
                            :filterable="true"
                            separator="-"
                            size="small"
                        />
                    </el-form-item>
                </div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="brand_cover"
                    label="图片素材:"
                >
                    <el-upload
                        :show-file-list="false"
                        :http-request="e=> {fnUploadImageOfCustomerLogo(e)}"
                        accept="image/*"
                        class="upload-demo"
                        drag
                        action="https://jsonplaceholder.typicode.com/posts/">
                        <img
                            v-if="formData.brand_cover"
                            :src="formData.brand_cover"
                            class="avatar">
                        <i
                            class="el-icon-upload"
                            v-if="!formData.brand_cover"/>
                        <div
                            class="el-upload__text"
                            v-if="!formData.brand_cover">将文件拖到此处，或<em>点击上传</em></div>
                        <div
                            class="el-upload__tip"
                            slot="tip">*只能上传jpg/png文件,图片尺寸大小916*748px,且不超过100kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="brand_title"
                    label="标题:"
                >
                    <el-input
                        placeholder="请填写标题,8到12个字"
                        v-model="formData.brand_title"
                        size="small"
                        class="task-input"
                        maxlength="12"
                    />
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="brand_info"
                    label="内容:"
                >
                    <div class="zd-text">
                        <el-input
                            type="textarea"
                            placeholder="描述文字不超过200字"
                            :autosize="{ minRows: 6, maxRows: 10}"
                            v-model="formData.brand_info"
                            style="width:492px"
                        />
                        <p
                            class="wrap"
                            style="color:#606266;font-size:14px"
                        >
                            <span :style="{color: formData.brand_info.length > 200 ? '#F56C6C' : ''}">
                                {{ formData.brand_info.length }}
                            </span>/200
                        </p>
                    </div>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="showTime"
                    label="展示时间:">
                    <el-date-picker
                        v-model="formData.showTime"
                        type="datetimerange"
                        range-separator="至"
                        size="small"
                        class="task-input"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间" />
                    <p style="display:inline-block;color:#999;margin-left:12px">*结束时间为空则永久存在</p>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="brand_sort"
                    label="排序:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.brand_sort"
                        size="small"
                        class="task-input"
                        type="number"
                    />
                    <span style="display:inline-block;color:#999;margin-left:12px">*数字越小排名越靠前</span>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    label="状态展示:">
                    <el-switch
                        v-model="formData.brand_show"
                        active-color="#13ce66"
                        active-text="展示"
                        :active-value="1"
                        :inactive-value="0"
                        inactive-text="隐藏"/>
                </el-form-item>
            </div>
            <div class="form-unit">
                <div class="operate-baar">
                    <el-button
                        size="medium"
                        v-show="id ? false : true"
                        @click="fnReset()">重置</el-button>
                    <el-button
                        size="medium"
                        type="primary"
                        @click="fnSubmit()">提交</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
export default {
    components: {},
    data() {
        const validateArray = (rule, value, callback) => {
            if (!value) {
                callback(new Error(rule.message));
            } else {
                if (!value[0]) {
                    callback(new Error(rule.message));
                    return ;
                }
                callback();
            }
        };

        const validateIndustry = (rule, value, callback) => {
            if(value.length == 0) {
                callback(new Error(rule.message));
            } else {
                callback();
            }
        };

        const validateLength = (rule, value, callback) => {
            if(value.length > 200) {
                callback(new Error('最多不可以超过200字'));
            } else {
                callback();
            }
        };


        return {
            industryList: [],//公司行业数据列表
            companyList: [],//合作客户公司数据列表
            submitting: false,
            id: '',
            formData: {
                brand_name: '',
                brand_people: '',
                // hire_no: '',
                company_name: '',
                category_id: [],
                brand_title: '',
                brand_info: '',
                brand_cover: '',
                brand_sort: '',
                showTime: [new Date().getTime(), ''],
                brand_show: 1
            },
            formRule: {
                brand_cover: [
                    { required: true, message: '轮播图图片不能为空', trigger: 'change' }
                ],
                brand_name: [
                    { required: true, message: '请输入品牌说名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字', trigger: 'blur' }
                ],
                brand_people: [
                    { required: true, message: '请填写姓名', trigger: 'change' }
                ],
                company_name: [
                    { required: true, message: '请填写客户品牌名', trigger: 'change' }
                ],
                // hire_no: [
                //     { required: true, message: '请填写公司名称', trigger: 'change' }
                // ],
                category_id: [
                    { validator: validateIndustry, message: '请选择公司行业', trigger: 'blur' },
                    { required: true, message: '请选择公司行业', trigger: 'change' }
                ],
                brand_info: [
                    { validator: validateLength, message: '最多不可以超过200字', trigger: 'blur' },
                    { required: true, message: '请填写内容', trigger: 'change' }
                ],
                brand_title: [
                    { required: true, message: '请填写标题', trigger: 'change' }
                ],
                showTime: [
                    { required: true, message: '开始时间不可以为空', trigger: 'blur' },
                    { validator: validateArray, message: '请填写正确的时间', trigger: 'blur' }
                ],
                brand_sort: [
                    { required: true, message: '请填写排序', trigger: 'blur' }
                ],
            },
            init: false,
            authResult: {}
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', [{ title: "APP后台"},{title: '官网'},{title: '官网自定义'},{title: '轮播图设置'}]);
        this.id = this.$route.query.id ? this.$route.query.id : '';

        if (!this.id) {
            this.init = true;
        }else{
            this.fnInitBannerInfo();
        }
    },
    mounted () {
        this.fnGetInstryList();
    },
    methods: {

        /**
         * 获取合作公司数据
         */
        // fnGetCompanyList (keyword) {
        //     this.$post('/wei4/hire_user%5Csuggest', {
        //         keyword: keyword
        //     }, resp => {
        //         if(resp.code == 1){
        //             this.companyList = resp.data.list;
        //         }else{
        //             this.$message({
        //                 type: 'warning',
        //                 message: resp.msg,
        //                 center: true
        //             });
        //         }
        //     });
        // },

        /**
         * 获取公司行业数据
         */
        fnGetInstryList () {
            this.$post('/wei4/hire_user%5Cget_category_list', {}, resp => {
                if(resp.code == 1){
                    let list = [];

                    for(let key in resp.data) {
                        list.push(resp.data[key]);
                    }
                    this.industryList = list;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },

        /**
         * 选择公司后查询公司行业
         */
        // fnGetIndustry () {
        //     this.fnGetCate(this.formData.hire_no);
        // },

        /**
         * 查询公司行业
         * 存在问题,不同的一级类目，相同的二级类目
         */
        // fnGetCate (hire_no) {
        //     this.$post('/wei4/hire_user%5Cget_list', {
        //         page_id: 1,
        //         hire_no: hire_no
        //     }, resp => {
        //         if(resp.code == 1){
        //             let category_name = resp.data.list[0].company.category_name;
        //             let cate = [];

        //             // console.log(category_name, 'category_name');
        //             this.industryList.forEach(option => {
        //                 if(option.children) {
        //                     option.children.forEach(element => {
        //                         if(element.title == category_name) {
        //                             cate.push(
        //                                 option.id,
        //                                 element.id
        //                             );
        //                         }
        //                     });
        //                 }
        //             });

        //             setTimeout(()=>{
        //                 if(cate.length == 2) {
        //                     this.formData.category_id = cate;
        //                 }
        //             },200);

        //         }else{
        //             this.$message({
        //                 type: 'warning',
        //                 message: resp.msg,
        //                 center: true
        //             });
        //         }
        //     });
        // },

        /**
         * 获取轮播图数据
         */
        fnInitBannerInfo() {
            this.$post('/student/stuhire_index%5Cbrand%5Cget', {
                brand_no: this.id
            }, resp => {
                if(resp.code == 1){
                    this.formData = {
                        ...resp.data,
                        showTime: [
                            resp.data.shelf_time == 0 ? '' : new Date(resp.data.shelf_time * 1000),
                            resp.data.expire_time == 0 ? '' : new Date(resp.data.expire_time * 1000)
                        ]
                    };
                    // this.fnGetCompanyList(resp.data.company_name);
                    this.init = true;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 提交数据
         */
        fnSubmit(){
            if(this.submitting){
                return ;
            }

            this.$refs.mainform.validate(valid => {
                if(valid){
                    this.submitting = true;

                    let data = {
                        brand_name: this.formData.brand_name,
                        brand_people: this.formData.brand_people,
                        // hire_no: this.formData.hire_no,
                        company_name: this.formData.company_name,
                        category_id: this.formData.category_id.length > 0 ? this.formData.category_id[1] : '',
                        brand_title: this.formData.brand_title,
                        brand_info: this.formData.brand_info,
                        brand_cover: this.formData.brand_cover,
                        shelf_time: this.formData.showTime.length > 0 ? (this.formData.showTime[0] == '' ? '' : new Date(this.formData.showTime[0]).getTime() / 1000) : '',
                        expire_time : this.formData.showTime.length > 0 ? (this.formData.showTime[1] == '' ? '' : new Date(this.formData.showTime[1]).getTime() / 1000) : '',
                        brand_sort: this.formData.brand_sort,
                        brand_show: this.formData.brand_show,
                    };

                    console.log(data, 'data');

                    if(this.id){
                        data.brand_no = this.id;

                        this.$post('/student/stuhire_index%5Cbrand%5Csave', data, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '修改成功'
                                });
                                this.$router.push({
                                    name: 'zdWebsitBrand',
                                    query: {
                                        tab: 1
                                    }
                                });
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }else{
                        this.$post('/student/stuhire_index%5Cbrand%5Csave', data, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '操作成功'
                                });
                                this.$router.push({
                                    name: 'zdWebsitBrand',
                                    query: {
                                        tab: 1
                                    }
                                });
                                return;
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }

                }
            });
        },

        /**
         * 上传图片
         */
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();
            let size = e.file.size;
            let m = Math.ceil(size / 1000) < 1000 ? Math.ceil(size / 1000) + 'kb' : (size / 1000000).toFixed(2)*1 + 'MB';

            if(size > 100000) {
                this.$message({
                    type: 'warning',
                    message: `图片尺寸大小建议小于100kb,当前图片大小${m}`,
                    center: true,
                    duration: 3000
                });
            }

            pic.append('file', e.file);

            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },

        fnUploadImageOfCustomerLogo(e) {
            this.fnUploadImage(e, (resp) => {
                this.formData.brand_cover = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },

        /**
         * 重置
         */
        fnReset(){
            this.$refs.mainform.resetFields();
        }
    }
};
</script>

<style lang="less" scoped>
    .avatar{
        width: 100%;
        height: 100%;;
    }
    .margin-top{
        margin-top: 15px;
    }
    .zdWebsitBrandChange {
      background: #fff;
      margin: 15px;
      margin-bottom: 0;
      padding: 30px;
      overflow: auto;
    }
    .form-unit {
      margin-bottom: 40px;
    }
    .form-title {
      font-size: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      line-height: 18px;
      padding: 0 10px;
      border-left: 2px solid #1890ff;
      margin-bottom: 20px;
    }
    .task-input {
      width: 492px !important;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }

    .operate-baar {
      width: 100%;
      text-align: center;
      margin-top: 168px;
    }
    .zd-text {
        display: flex;
        flex-direction: column;
        position: relative;
        width: 492px;
        .wrap {
            position: absolute;
            right: 18px;
            bottom: -4px;
        }
    }
</style>
<style lang="less">
</style>
